package vn.edu.uit.chemistry;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import vn.edu.uit.chemistry.dragdrop.DragController;
import vn.edu.uit.chemistry.dragdrop.DragLayer;
import vn.edu.uit.chemistry.model.GuiTaiLieuAdapter;
import vn.edu.uit.chemistry.model.GuiTaiLieuAdapter.HocSinhHolder;
import vn.edu.uit.chemistry.model.ThongTinHocSinh;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TaiLieu extends Activity {
	private DragController mDragController; // Object that sends out drag-drop
	// events while a view is being
	// moved.
	private DragLayer mDragLayer; // The ViewGroup that supports drag-drop.
	private boolean mLongClickStartsDrag = false; // If true, it takes a long
	// click to start the drag
	// operation.
	// Otherwise, any touch
	// event starts a drag.

	private GridView gridView;
	private static final int CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST;

	public static final boolean Debugging = false;

	private Button btnBack;
	private Button btnGroup;
	private Button ibDel;
	private RelativeLayout rlFooter;

	ArrayAdapter<String> adapter;

	public static final String ACTION_WIDGET = "vn.edu.uit.wifi_transfering.Transferation.ACTION_WIDGET";
	private static final String PREFS_NAME = "ManagerPrefsFile"; // user
																	// preference
																	// file name
	private static final String PREFS_HIDDEN = "hidden";
	private static final String PREFS_COLOR = "color";
	private static final String PREFS_THUMBNAIL = "thumbnail";
	private static final String PREFS_SORT = "sort";

	private FileManager mFileMag;
	private EventHandler mHandler;
	private EventHandler.TableRow mTable;

	private SharedPreferences mSettings;
	private boolean mReturnIntent = false;
	private TextView mPathLabel, mDetailLabel, mStorageLabel;

	private boolean isLongClick = false;
	ArrayList<ThongTinHocSinh> listThongTinHocSinh = new ArrayList<ThongTinHocSinh>();

	/**
	 * onCreate - called when the activity is first created.
	 * 
	 * Creates a drag controller and sets up three views so click and long click
	 * on the views are sent to this activity. The onLongClick method starts a
	 * drag sequence.
	 * 
	 */

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		mDragController = new DragController(this);

		setContentView(R.layout.screen_tai_lieu);

		/* read settings */
		mSettings = getSharedPreferences(PREFS_NAME, 0);
		boolean hide = mSettings.getBoolean(PREFS_HIDDEN, false);
		boolean thumb = mSettings.getBoolean(PREFS_THUMBNAIL, true);
		int color = mSettings.getInt(PREFS_COLOR, -1);
		int sort = mSettings.getInt(PREFS_SORT, 2);

		mFileMag = new FileManager();
		mFileMag.setShowHiddenFiles(hide); // khoi tao ban dau la ko an
		mFileMag.setSortType(sort); // khoi tao ban dau la sap xep tang dan theo
									// dung luong

		if (savedInstanceState != null)
			mHandler = new EventHandler(TaiLieu.this, mFileMag,
					savedInstanceState.getString("location"));
		else
			mHandler = new EventHandler(TaiLieu.this, mFileMag); // tai
																	// day
																	// khoi
		// tao duong dan
		// den thu muc
		// hien tai de
		// lay danh sach

		mHandler.setTextColor(color);
		mHandler.setShowThumbnails(thumb); // khoi tao ban dau la tao thumbnail
		mTable = mHandler.new TableRow(); // tao mot danh sach theo duong dan
											// khoi tao ban sau

		btnBack = (Button) findViewById(R.id.back_button);
		btnBack.setOnClickListener(mHandler);

		btnGroup = (Button) findViewById(R.id.btnGroup);
		btnGroup.setEnabled(true);
		btnGroup.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(0);
			}
		});

		rlFooter = (RelativeLayout) findViewById(R.id.rlFooter);
		rlFooter.setVisibility(View.GONE);

		ibDel = (Button) findViewById(R.id.ibDelSend);
		ibDel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				SharedPreferences prefs = getSharedPreferences("DSGui", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.clear();
				editor.commit();
				sendFile(false);
			}
		});

		mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
		mDragLayer.setDragController(mDragController);
		mDragController.addDropTarget(mDragLayer);

		gridView = (GridView) findViewById(R.id.gridview);

		gridView.setOnItemClickListener(listClickedItem);
		gridView.setOnItemLongClickListener(listLongClickListener);
		mHandler.setGridAdapter(mTable);
		gridView.setAdapter(mTable);

	}

	public void sendFile(boolean isSent) {
		if (isSent) {
			isLongClick = true;
			rlFooter.setVisibility(View.VISIBLE);
			rlFooter.postDelayed(onEverySecond, 0);
			btnGroup.setEnabled(false);
		} else {
			SharedPreferences prefs = getSharedPreferences("DSGui", 0);
			SharedPreferences.Editor editor = prefs.edit();
			editor.clear();
			editor.commit();
			isLongClick = false;
			rlFooter.setVisibility(View.GONE);
			rlFooter.removeCallbacks(onEverySecond);
			btnGroup.setEnabled(true);
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString("location", mFileMag.getCurrentDir());
	}
	
	private void returnIntentResults(File data) {
		mReturnIntent = false;
		
		Intent ret = new Intent();
		ret.setData(Uri.fromFile(data));
		setResult(RESULT_OK, ret);
		
		finish();
	}

	public OnItemClickListener listClickedItem = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			// TODO Auto-generated method stub
			final String item = mHandler.getData(position);
			File file = new File(mFileMag.getCurrentDir() + "/" + item);
			String item_ext = null;

			try {
				item_ext = item.substring(item.lastIndexOf("."), item.length());

			} catch (IndexOutOfBoundsException e) {
				item_ext = "";
			}

			if (file.isDirectory()) {
				if (file.canRead()) {
					mHandler.stopThumbnailThread();
					// item = sdcard
					mHandler.updateDirectory(mFileMag.getNextDir(item, false));

					/*
					 * set back button switch to true (this will be better
					 * implemented later)
					 */
					// if (!mUseBackKey)
					// mUseBackKey = true;

				} else {
					Toast.makeText(TaiLieu.this,
							"Can't read folder due to permissions",
							Toast.LENGTH_SHORT).show();
				}
			} /*music file selected--add more audio formats*/
	    	else if (item_ext.equalsIgnoreCase(".mp3") || 
	    			 item_ext.equalsIgnoreCase(".m4a")||
	    			 item_ext.equalsIgnoreCase(".mp4")) {
	    		
	    		if(mReturnIntent) {
	    			returnIntentResults(file);
	    		} else {
	    			Intent i = new Intent();
   				i.setAction(android.content.Intent.ACTION_VIEW);
   				i.setDataAndType(Uri.fromFile(file), "audio/*");
   				startActivity(i);
	    		}
	    	}
	    	
	    	/*photo file selected*/
	    	else if(item_ext.equalsIgnoreCase(".jpeg") || 
	    			item_ext.equalsIgnoreCase(".jpg")  ||
	    			item_ext.equalsIgnoreCase(".png")  ||
	    			item_ext.equalsIgnoreCase(".gif")  || 
	    			item_ext.equalsIgnoreCase(".tiff")) {
	 			    		
	    		if (file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
			    		Intent picIntent = new Intent();
			    		picIntent.setAction(android.content.Intent.ACTION_VIEW);
			    		picIntent.setDataAndType(Uri.fromFile(file), "image/*");
			    		startActivity(picIntent);
	    			}
	    		}
	    	}
	    	
	    	/*video file selected--add more video formats*/
	    	else if(item_ext.equalsIgnoreCase(".m4v") || 
	    			item_ext.equalsIgnoreCase(".3gp") ||
	    			item_ext.equalsIgnoreCase(".wmv") || 
	    			item_ext.equalsIgnoreCase(".mp4") || 
	    			item_ext.equalsIgnoreCase(".ogg") ||
	    			item_ext.equalsIgnoreCase(".wav")) {
	    		
	    		if (file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
	    				Intent movieIntent = new Intent();
			    		movieIntent.setAction(android.content.Intent.ACTION_VIEW);
			    		movieIntent.setDataAndType(Uri.fromFile(file), "video/*");
			    		startActivity(movieIntent);
	    			}
	    		}
	    	}
	    	
	    	/*pdf file selected*/
	    	else if(item_ext.equalsIgnoreCase(".pdf")) {
	    		
	    		if(file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
			    		Intent pdfIntent = new Intent();
			    		pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
			    		pdfIntent.setDataAndType(Uri.fromFile(file), 
			    								 "application/pdf");
			    		
			    		try {
			    			startActivity(pdfIntent);
			    		} catch (ActivityNotFoundException e) {
			    			Toast.makeText(getApplicationContext(), "Sorry, couldn't find a pdf viewer", 
									Toast.LENGTH_SHORT).show();
			    		}
		    		}
	    		}
	    	}
	    	
	    	/*Android application file*/
	    	else if(item_ext.equalsIgnoreCase(".apk")){
	    		
	    		if(file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
		    			Intent apkIntent = new Intent();
		    			apkIntent.setAction(android.content.Intent.ACTION_VIEW);
		    			apkIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		    			startActivity(apkIntent);
	    			}
	    		}
	    	}
	    	
	    	/* HTML file */
	    	else if(item_ext.equalsIgnoreCase(".html")) {
	    		
	    		if(file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
		    			Intent htmlIntent = new Intent();
		    			htmlIntent.setAction(android.content.Intent.ACTION_VIEW);
		    			htmlIntent.setDataAndType(Uri.fromFile(file), "text/html");
		    			
		    			try {
		    				startActivity(htmlIntent);
		    			} catch(ActivityNotFoundException e) {
		    				Toast.makeText(getApplicationContext(), "Sorry, couldn't find a HTML viewer", 
		    									Toast.LENGTH_SHORT).show();
		    			}
	    			}
	    		}
	    	}
	    	
	    	/* text file*/
	    	else if(item_ext.equalsIgnoreCase(".txt")) {
	    		
	    		if(file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
		    			Intent txtIntent = new Intent();
		    			txtIntent.setAction(android.content.Intent.ACTION_VIEW);
		    			txtIntent.setDataAndType(Uri.fromFile(file), "text/plain");
		    			
		    			try {
		    				startActivity(txtIntent);
		    			} catch(ActivityNotFoundException e) {
		    				txtIntent.setType("text/*");
		    				startActivity(txtIntent);
		    			}
	    			}
	    		}
	    	}
	    	
	    	/* generic intent */
	    	else {
	    		if(file.exists()) {
	    			if(mReturnIntent) {
	    				returnIntentResults(file);
	    				
	    			} else {
			    		Intent generic = new Intent();
			    		generic.setAction(android.content.Intent.ACTION_VIEW);
			    		generic.setDataAndType(Uri.fromFile(file), "text/plain");
			    		
			    		try {
			    			startActivity(generic);
			    		} catch(ActivityNotFoundException e) {
			    			Toast.makeText(getApplicationContext(), "Sorry, couldn't find anything " +
			    						   "to open " + file.getName(), 
			    						   Toast.LENGTH_SHORT).show();
			    		}
	    			}
	    		}
	    	}
		}
	};

	/**
	 * Build a menu for the activity.
	 * 
	 */

	public OnItemLongClickListener listLongClickListener = new OnItemLongClickListener() {

		public boolean onItemLongClick(AdapterView<?> parent, View v, int pos,
				long id) {
			final String item = mHandler.getData(pos);
			File file = new File(mFileMag.getCurrentDir() + "/" + item);
			String item_ext = null;

			try {
				item_ext = item.substring(item.lastIndexOf("."), item.length());
			} catch (IndexOutOfBoundsException e) {
				item_ext = "";
			}

			if (file.isFile() && isLongClick) {
				String[] content = ((String) v.getContentDescription())
						.split("#");
				if (content[0].equals("Folder")) {
					Toast.makeText(getBaseContext(), content[0],
							Toast.LENGTH_SHORT).show();
					return false;
				}

				boolean handledHere = false;

				handledHere = startDrag(v);
			}
			return false;
		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {

		Context ctx = TaiLieu.this;

		listThongTinHocSinh = new ArrayList<ThongTinHocSinh>();
		ThongTinHocSinh _tthsAll = new ThongTinHocSinh();
		_tthsAll.setTenHS("Tất cả");
		_tthsAll.setMshs("00000000");
		_tthsAll.setHost("192.168.0.1");
		_tthsAll.setSent(true);
		listThongTinHocSinh.add(_tthsAll);

		SharedPreferences prefs = ctx.getSharedPreferences("DSHS", 0);
		Map<String, ?> keys = prefs.getAll();
		for (Map.Entry<String, ?> entry : keys.entrySet()) {
			String[] values = entry.getValue().toString().split("#");
			if (values[1].length() > 1) {
				ThongTinHocSinh tths = new ThongTinHocSinh();
				tths.setMshs(entry.getKey());
				tths.setTenHS(values[0]);
				tths.setHost(values[1]);
				tths.setSent(true);
				listThongTinHocSinh.add(tths);
			}
		}

		final Dialog dialog = new Dialog(ctx);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_gui_tai_lieu);
		dialog.setCancelable(true);

		TextView tvThongBao = (TextView) dialog.findViewById(R.id.tvThongBao);
		ListView lvDSGui = (ListView) dialog.findViewById(R.id.lvDSGui);
		final Button btnOK = (Button) dialog.findViewById(R.id.btnOK);
		btnOK.setEnabled(false);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);

		if (listThongTinHocSinh.size() <= 1) {
			tvThongBao.setVisibility(View.VISIBLE);
			lvDSGui.setVisibility(View.GONE);
			btnOK.setEnabled(false);
		} else {
			tvThongBao.setVisibility(View.GONE);
			lvDSGui.setVisibility(View.VISIBLE);
			lvDSGui.setAdapter(new GuiTaiLieuAdapter(ctx, listThongTinHocSinh));
			lvDSGui.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View v, int pos,
						long id) {

					HocSinhHolder holder;
					if (pos == 0) {
						holder = (HocSinhHolder) parent.getChildAt(0).getTag();
						int isInvi = holder.imgDiemDanh.getVisibility();
						if (isInvi == View.INVISIBLE) {
							for (int i = 0; i < parent.getChildCount(); i++) {
								HocSinhHolder _holder = (HocSinhHolder) parent
										.getChildAt(i).getTag();
								_holder.imgDiemDanh.setVisibility(View.VISIBLE);
								listThongTinHocSinh.get(i).setSent(true);
							}
						} else if (isInvi == View.VISIBLE) {
							for (int i = 0; i < parent.getChildCount(); i++) {
								HocSinhHolder _holder = (HocSinhHolder) parent
										.getChildAt(i).getTag();
								_holder.imgDiemDanh
										.setVisibility(View.INVISIBLE);
								listThongTinHocSinh.get(i).setSent(false);
							}
						}
					} else {
						listThongTinHocSinh.get(0).setSent(false);
						holder = (HocSinhHolder) parent.getChildAt(0)
								.getTag();
						holder.imgDiemDanh.setVisibility(View.INVISIBLE);
						holder = (HocSinhHolder) parent.getChildAt(pos)
								.getTag();
						int isInvi = holder.imgDiemDanh.getVisibility();
						if (isInvi == View.INVISIBLE) {
							HocSinhHolder _holder = (HocSinhHolder) parent
									.getChildAt(pos).getTag();
							_holder.imgDiemDanh.setVisibility(View.VISIBLE);
							listThongTinHocSinh.get(pos).setSent(true);
						} else if (isInvi == View.VISIBLE) {
							HocSinhHolder _holder = (HocSinhHolder) parent
									.getChildAt(pos).getTag();
							_holder.imgDiemDanh.setVisibility(View.INVISIBLE);
							listThongTinHocSinh.get(pos).setSent(false);
						}
					}

					int count = 0;
					for (int j = 0; j < listThongTinHocSinh.size(); j++) {
						if (listThongTinHocSinh.get(j).isSent()) {
							count++;
							break;
						}
					}
					
					if (count > 0) {
						btnOK.setEnabled(true);
					} else {
						btnOK.setEnabled(false);
					}
				}
			});
			
		}

		btnOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				sendFile(true);
				removeDialog(0);
				Context ctx = TaiLieu.this;
				SharedPreferences prefs = ctx.getSharedPreferences("DSGui", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.clear();
				editor.commit();
				
				for (int i = 1; i < listThongTinHocSinh.size(); i++) {
					if (listThongTinHocSinh.get(i).isSent()) {
						String mshs = listThongTinHocSinh.get(i).getMshs();
						String tenHS = listThongTinHocSinh.get(i).getTenHS();
						String host = listThongTinHocSinh.get(i).getHost();
						editor.putString(host, mshs+"#"+tenHS+"#0");
					}
				}
				editor.commit();
				
				String temp = mFileMag.getCurrentDir();
				mHandler.updateDirectory(mFileMag.getNextDir(temp, true));
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				removeDialog(0);
			}
		});

		return dialog;
	}


	/**
	 * Start dragging a view.
	 * 
	 */

	public boolean startDrag(View v) {
		// Let the DragController initiate a drag-drop sequence.
		// I use the dragInfo to pass along the object being dragged.
		// I'm not sure how the Launcher designers do this.
		Object dragInfo = v;
		mDragController.startDrag(v, mDragLayer, dragInfo,
				DragController.DRAG_ACTION_MOVE);
		return true;
	}

	public Runnable onEverySecond = new Runnable() {
		public void run() {
			// do real work here
			if (isLongClick) {
				new GetCoodinationAsyncTask().execute();
			}
		}
	};

	final class GetCoodinationAsyncTask extends AsyncTask<Void, Void, Void> {

		int xCo = 0;
		int yCo = 0;

		public GetCoodinationAsyncTask() {

		}

		@Override
		protected Void doInBackground(Void... params) {
			xCo = mDragController.getX;
			yCo = mDragController.getY;
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Log.d("count", xCo + "-" + yCo);
			DisplayMetrics metrics = getResources().getDisplayMetrics();
			int height = metrics.heightPixels;
			if (yCo >= (height -  50)) {
				rlFooter.setBackgroundColor(getResources().getColor(
						R.color.orange));
			} else {
				rlFooter.setBackgroundColor(getResources().getColor(
						R.color.light_orange));
			}

			rlFooter.postDelayed(onEverySecond, 0);
		}

	}

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg
	 *            String
	 * @return void
	 */

	public void toast(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	} // end toast

	/**
	 * Send a message to the debug log and display it using Toast.
	 */

	public void trace(String msg) {
		if (!Debugging)
			return;
		Log.d("DragActivity", msg);
		toast(msg);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}
}
